#include "BitMap.h"

// 位图的方法
typedef struct BitMapMethod
{
    BitMapMethodPtr_t _set;
    BitMapMethodPtr_t _reset;
    BitMapMethodPtr_t _test;

}BitMapMethod;

// 位图的属性
typedef struct BitMapField
{
    BitMap_t* _ptr;
    size_t _size;

}BitMapField;
bool Set(struct BitMapField* field,size_t x)
{

    if(x>=field->_size)
        return false;

    int group=x/BITCOUNT;
    int index=x%BITCOUNT;

    (field->_ptr)[group]|= (1<<index);

    return true;
}

bool ReSet(struct BitMapField* field,size_t x)
{
    if(x>=field->_size)
        return false;

    int group=x/BITCOUNT;
    int index=x%BITCOUNT;

    (field->_ptr)[group]&= ~(1<<index);
    return true;
}

bool Test(struct BitMapField* field,size_t x)
{
    
    if(x>=field->_size)
        return false;

    int group=x/BITCOUNT;
    int index=x%BITCOUNT;

    int ret=(field->_ptr)[group]&(1<<index);

    return ret==1;
}


// 位图
typedef struct BitMap
{
    BitMapField* _field;
    BitMapMethod* _method;
}BitMap;

BitMap* CreateBitMap(size_t size)
{
    BitMap* bitmap=(BitMap*)malloc(sizeof(BitMap));

    bitmap->_field=(BitMapField*)malloc(sizeof(BitMapField));
    if(bitmap->_field==NULL)
    {
        perror("malloc");
        return NULL;
    }

    bitmap->_method=(BitMapMethod*)malloc(sizeof(BitMapMethod));
    if(bitmap->_method==NULL)
    {
        perror("malloc");
        return NULL;
    }
    size_t count=(size/(BITCOUNT+1))+1;

    bitmap->_field->_ptr=(BitMap_t*)malloc(sizeof(BitMap_t)*count);
    if(bitmap->_method==NULL)
    {
        perror("malloc");
        return NULL;
    }

    for(size_t i=0;i<count;i++)
    {
        bitmap->_field->_ptr[i]=0;
    }

    bitmap->_field->_size=size;

    bitmap->_method->_set=&Set;
    bitmap->_method->_reset=&ReSet;
    bitmap->_method->_test=&Test;

    return bitmap;
}

